<template>
  <div class="main_box" style="padding: 10px">
    <el-card class="detail-wrapper">
      <div slot="header" style="display: flex;align-items: end;">
        <div class="header">
          <i @click="returnList" class="el-icon-arrow-left"></i>
          <div class="separater">|</div>
          <div class="title">订单详情</div>
        </div>
        <div class="rightBtn">
          <el-button v-if="dataInfo.payState !== 1" size="mini" type="primary" @click="show = true"> 查看交易记录
          </el-button>
          <el-button size="mini" type="primary" v-has="permissionPunchClock" @click="punchClock.show = true"
            style="margin-right: 20px">代打卡</el-button>
          <el-button size="mini" type="primary" v-has="permissionCheck" @click="handleGotoCustomerList">查看积分</el-button>
          <el-button size="mini" type="primary" v-if="orderAttrs.length > 0" @click="showForm = true">修改附加信息</el-button>
          <el-button type="primary" size="mini" @click="getLocationList('Y')"
            v-if="dataInfo.alarmEquip && dataInfo.alarmEquip.equipType === 1">报警定位记录</el-button>
          <el-button v-if="dataInfo.beeperId" type="primary" size="mini" @click="sendNotify">通知呼叫器</el-button>
        </div>
      </div>

      <div class="content">
        <div class="title">订单概要</div>
        <el-row>
          <div class="item">
            <div>订单编号:</div>
            <div>
              {{ dataInfo.orderNo }}
            </div>
          </div>
          <div class="item">
            <div>订单类型:</div>
            <div>
              {{ formatOrderType(dataInfo.orderType) }}
              <span style="color: red; font-size: 16px" v-if="dataInfo.orderType === 8"> - {{
                $Filters.formatAlarmType(dataInfo.alarmType) }}</span>
            </div>
          </div>
          <div class="item">
            <div>订单来源:</div>
            <div>
              {{ $Filters.formatOrderSource(dataInfo.orderSource) }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.invoice">
            <div>订单发票:</div>
            <div>
              <el-tooltip effect="dark" content="查看订单发票" placement="top">
                <span class="el-icon-view" @click="showInvoice = true"></span>
              </el-tooltip>
            </div>
          </div>
          <div class="item">
            <div>订单备注:</div>
            <div>
              {{ dataInfo.orderRemark || "无" }}
              <el-tooltip effect="dark" content="修改订单备注" placement="top">
                <span class="el-icon-edit" @click="() => {
                  showRemark = true
                  editRemark = dataInfo.orderRemark
                }"></span>
              </el-tooltip>
            </div>
          </div>
          <div class="item" v-if="dataInfo.voiceRemark">
            <div>用户语音备注:</div>
            <div>
              <span :class="voiceRemark.isPlaying() ? 'el-icon-video-pause' : 'el-icon-video-play'"
                v-if="dataInfo.voiceRemark && dataInfo.voiceRemark.endsWith('.amr')"
                @click="playVoiceRemark('voiceRemark')"></span>
              <audio v-else Controls :src="dataInfo.voiceRemark"></audio>
            </div>
          </div>
          <div class="item" v-if="dataInfo.businessVoice">
            <div>商户语音备注:</div>
            <div>
              <span :class="businessVoice.isPlaying() ? 'el-icon-video-pause' : 'el-icon-video-play'"
                v-if="dataInfo.businessVoice && dataInfo.businessVoice.endsWith('.amr')"
                @click="playVoiceRemark('businessVoice')"></span>
              <audio v-else Controls :src="dataInfo.businessVoice"></audio>
            </div>
          </div>
          <div class="item">
            <div>订单状态:</div>
            <div>
              {{ formatOrderState(dataInfo.orderState) }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.errorState">
            <div>异常状态:</div>
            <div>
              <span v-if="dataInfo.errorState === 1" style="color: red">超时未接单</span>
              <span v-if="dataInfo.errorState === 2" style="color: red">商户取消</span>
              <span v-if="dataInfo.errorState === 3" style="color: red">用户申请取消</span>
            </div>
          </div>
          <div class="item" v-if="dataInfo.cancelReason">
            <div>取消原因:</div>
            <div>
              {{ dataInfo.cancelReason }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.deliveryFee">
            <div>配送费:</div>
            <div>
              {{ dataInfo.deliveryFee }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.packageFee">
            <div>包装费:</div>
            <div>
              {{ dataInfo.packageFee }}
            </div>
          </div>

          <div class="item">
            <div>支付方式:</div>
            <div>
              {{ formatPayType(dataInfo.payType) }}
            </div>
          </div>
          <!-- <div class="item" v-if="dataInfo.payType == 2">
            <div>
              支付时间:
            </div>
            <div>
              {{ dataInfo.payTime }}
            </div>
          </div> -->
          <div class="item">
            <div>支付状态:</div>
            <div class="pay-state">
              {{ formatPayState(dataInfo.payState) }}
              <span v-if="dataInfo.appointmentState > 0">{{ formatAppointmentState(dataInfo.appointmentState) }}</span>

            </div>
          </div>
          <div class="item" v-if="dataInfo.payDate">
            <div>支付日期:</div>
            <div>
              {{ dataInfo.payDate }}
            </div>
          </div>
          <div class="item">
            <div>下单日期:</div>
            <div>
              {{ dataInfo.createDate }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.acceptDate">
            <div>接单日期:</div>
            <div>
              {{ dataInfo.acceptDate }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.expectedTime && dataInfo.orderState <= 11 && dataInfo.serviceMode !== 1">
            <div>预计到达时间:</div>
            <div style="color: red; width: fit-content" @click="showTimeDialog">
              {{ $Utils.getOptimizeDateTwo(dataInfo.expectedTime) + (dataInfo.deliveryTime ? '(点击修改)' : '') }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.completeDate">
            <div>完成日期:</div>
            <div>
              {{ dataInfo.completeDate }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.cancelDate">
            <div>取消日期:</div>
            <div>
              {{ dataInfo.cancelDate }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.alarmEquip">
            <div>报警设备:</div>
            <div>{{ formatEquipType(dataInfo.alarmEquip.equipType) }} - {{ dataInfo.alarmEquip.equipName }} - {{
              dataInfo.alarmEquip.equipCode }}</div>
          </div>
          <div class="item" v-if="dataInfo.alarmEquip">
            <div>报警定位地址:</div>
            <div>
              {{ dataInfo.currentAddress }}

            </div>
          </div>
          <div class="item" v-if="dataInfo.remark">
            <div>接单时备注：</div>
            <div>{{ dataInfo.remark }}</div>
          </div>
          <div class="item" v-if="dataInfo.discountOld">
            <div>养老金最高抵扣额:</div>
            <div>
              -￥{{ dataInfo.discountOld }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.rebateOld">
            <div>养老金返利额:</div>
            <div>
              +￥{{ dataInfo.rebateOld }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.discountPmc">
            <div>物业金最高抵扣额:</div>
            <div>
              -￥{{ dataInfo.discountPmc }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.rebatePmc">
            <div>物业金返利额:</div>
            <div>
              +￥{{ dataInfo.rebatePmc }}
            </div>
          </div>
        </el-row>
        <div enter-class="title" v-if="urls.length">订单图片</div>
        <el-row class="image-wrapper" v-if="urls.length">
          <el-image v-for="(item, index) in urls" :src="item" fit="cover" :preview-src-list="urls" :key="index">
          </el-image>
        </el-row>
        <template v-for="item in orderAttrs">
          <div class="title">{{ item.name || '附加信息' }}</div>
          <el-row>
            <div class="attr-introduce" v-if="item.introduce">
              {{ item.introduce }}
            </div>
            <template v-for="item2 in item.list">
              <div class="item">
                <div>{{ item2.attrName }}:</div>
                <div
                  v-if="item2.fieldType === 1 || item2.fieldType === 2 || item2.fieldType === 3 || item2.fieldType === 6 || item2.fieldType === 7">
                  {{ item2.value }}
                </div>
                <div v-else-if="item2.fieldType === 4">
                  <el-image v-for="(item3, index3) in item2.value" :key="index3" fit="cover" :src="item3" alt=""
                    :preview-src-list="item2.value" :initial-index="index3"></el-image>
                </div>
                <div v-else-if="item2.fieldType === 5">
                  <video v-if="item2.value" controls :src="item2.value"></video>
                </div>
                <div v-else-if="item2.fieldType === 8">
                  <audio Controls :src="item2.value"></audio>
                </div>
              </div>
            </template>
          </el-row>
        </template>

        <div class="title">客户详情</div>
        <el-row>
          <div class="item">
            <div>客户姓名:</div>
            <div style="display: flex">
              <span style="margin-right: 40px">{{ dataInfo.linkName }}</span>

            </div>
          </div>
          <div class="item">
            <div>客户电话:</div>
            <div>
              {{ dataInfo.phone
              }}<span v-if="!showWholePhone" class="el-icon-view" @click="
  dataInfo.phone = dataInfo.wholePhone;
showWholePhone = true;
"></span>
            </div>
          </div>
          <div class="item">
            <div>详细地址:</div>
            <div>
              {{ dataInfo.provinceName }}{{ dataInfo.cityName }}{{ dataInfo.areaName }}{{ dataInfo.streetName }}{{
                dataInfo.address }}{{ dataInfo.buildName }}{{ dataInfo.unitName }}{{ dataInfo.floorName
  }}{{ dataInfo.houseNumber }}
            </div>
          </div>
          <div class="item">
            <div>标签:</div>
            <div>
              {{ dataInfo.tags }}
            </div>
          </div>
          <div class="item">
            <div>呼叫器名称:</div>
            <div>
              {{ dataInfo.equipName }}
            </div>
          </div>
          <div class="item">
            <div>呼叫器编号:</div>
            <div>
              {{ dataInfo.equipCode }}
              <el-tooltip effect="dark" content="查看呼叫器二维码" placement="top">
                <!-- <el-button size="mini" type="primary" icon="el-icon-picture-outline"></el-button> -->
                <span class="el-icon-picture-outline" @click="getBeeperCode"></span>
              </el-tooltip>
              <el-image ref="preview" style="display: none" :preview-src-list="srcList"></el-image>
            </div>
          </div>
          <div class="item" v-if="dataInfo.localeInfo" style="width: 100%; color: red">
            <el-collapse>
              <el-collapse-item title="查看场所详情">
                <div class="item">
                  <div>场所类型:</div>
                  <div>
                    {{ formatLocaleType(dataInfo.localeInfo.localeType) }}
                  </div>
                </div>
                <div class="item">
                  <div>场所地址:</div>
                  <div>
                    {{ address }}
                  </div>
                </div>
                <div class="item">
                  <div>物业名称:</div>
                  <div>
                    {{ dataInfo.localeInfo.pmcName }}
                  </div>
                </div>
                <div class="item">
                  <div>物业联系电话:</div>
                  <div>
                    {{ dataInfo.localeInfo.pmcPhone }}
                    <span v-if="dataInfo.localeInfo.pmcPhoneTwo"> / {{ dataInfo.localeInfo.pmcPhoneTwo }}（备用）</span>
                  </div>
                </div>
                <div class="item">
                  <div>第一紧急联系人:</div>
                  <div>
                    {{ dataInfo.localeInfo.oneName }} -
                    {{ dataInfo.localeInfo.onePhone }}
                  </div>
                </div>
                <div class="item">
                  <div>第二紧急联系人:</div>
                  <div>
                    {{ dataInfo.localeInfo.twoName }} -
                    {{ dataInfo.localeInfo.twoPhone }}
                  </div>
                </div>
                <div class="item">
                  <div>第三紧急联系人:</div>
                  <div>
                    {{ dataInfo.localeInfo.threeName }} -
                    {{ dataInfo.localeInfo.threePhone }}
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-row>
        <div class="title">产品详情</div>
        <el-row>
          <el-table :data="goodsList" :row-class-name="getRowClass" :expand-row-keys="rowkeys" :row-key="handleRowKey">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table class="inner-table" :data="props.row.ogrelations || []">
                  <el-table-column prop="name" label="产品名称" align="center"> </el-table-column>
                  <el-table-column prop="sku" label="规格名" align="center">
                    <template slot-scope="scope">
                      <div>
                        {{ scope.row.sku === '无' ? '' : scope.row.sku || '' }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="产品图片" align="center">
                    <template slot-scope="scope2">
                      <div class="img-wrapper">
                        <el-image style="width: 100px; height: 60px" fit="cover" :src="scope2.row.images" alt=""
                          :preview-src-list="[scope2.row.images]"></el-image>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" align="center" width="100px"> </el-table-column>
            <el-table-column label="产品图片" align="center" width="150">
              <template slot-scope="scope">
                <div class="img-wrapper">
                  <el-image style="width: 100px; height: 60px" fit="cover" :src="scope.row.images" alt=""
                    :preview-src-list="[scope.row.images]"></el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="产品名称" align="center"> </el-table-column>

            <el-table-column prop="strSpecVal" label="规格" align="center" width="150">
              <template slot-scope="scope">
                <div>
                  {{ (scope.row.strSpecVal && scope.row.strSpecVal) !== '无' ? scope.row.strSpecVal : '' }}
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="nums" label="数量" align="center" width="100"> </el-table-column>
            <el-table-column prop="price" label="原价" align="center" width="100"> </el-table-column>
            <el-table-column prop="salePrice" label="售价" align="center" width="100">
              <template slot-scope="scope">
                <div style="color: red" v-if="scope.row.activeDiscount">活动价：{{ scope.row.activePrice }}</div>
                <div v-else>
                  {{ scope.row.salePrice }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="packageFee" label="包装费" align="center" width="100"> </el-table-column>
            <el-table-column prop="deliveryFee" label="配送费" align="center" width="100"> </el-table-column>
            <el-table-column prop="discount" label="商户折扣比例(%)" align="center" width="120"> </el-table-column>
            <el-table-column label="所属部门" align="center">
              <template slot-scope="scope">
                <div>
                  {{ departNames }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="产品分类" align="center">
              <template slot-scope="scope"> {{ scope.row.serverClassifyName }}-{{ scope.row.thirdClassifyName }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="预计到达时间" align="center" width="200" v-if="dataInfo.orderState<=11">
              <template slot-scope="scope">
                <div v-if="scope.row.expectedTime">
                  {{ $Utils.getOptimizeDateTwo(scope.row.expectedTime) }}
                </div>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <el-button v-has="permissionModifyPrice" v-if="dataInfo.payState < 10 && dataInfo.orderState < 15"
                  @click="handleClickRefund(scope.row, scope.$index)" size="mini">退货退款 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <div class="title" v-if="dataInfo.orderType === 11">服务员任务列表</div>
        <el-row v-if="dataInfo.orderType === 11">
          <!-- 姓名 电话（可拨打） 任务 -->
          <el-table :data="rescueList" :row-class-name="getRowClass" :expand-row-keys="rowkeys" :row-key="handleRowKey">
            <el-table-column prop="waiterName" label="姓名" align="center" width="auto"> </el-table-column>
            <el-table-column prop="phone" label="电话" align="center" width="auto"> </el-table-column>
            <el-table-column prop="firstAidDate" label="救援时间" align="center" width="auto"> </el-table-column>
            <el-table-column prop="jobType" label="救援类型" align="center" width="auto">
              <template slot-scope="scope">
                <div>{{ scope.row.jobType | jobTypeFilter }}</div>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <div class="title" v-if="dataInfo.orderType === 3">计时详情</div>
        <el-row v-if="dataInfo.orderType === 3">
          <div class="item">
            <div>计时类型:</div>
            <div>
              {{ dataInfo.timingType === 1 ? '固定时长' : '非固定时长' }}
            </div>
          </div>

          <div class="item" v-if="dataInfo.timingState">
            <div>计时状态:</div>
            <div>
              <div v-if="dataInfo.timingState === 1" style="color: #07c160">计时使用中</div>
              <div v-if="dataInfo.timingState === 2" style="color: red">计时结束</div>
              <div v-if="dataInfo.timingState === 3" style="color: red">超额结束</div>
            </div>
          </div>
          <div class="item" v-if="dataInfo.timingType === 1">
            <div>可用时长:</div>
            <div>
              {{ dataInfo.rentTime + formatTimeUnit(dataInfo.rentUnit) }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.timingType === 2">
            <div>起步价:</div>
            <div>{{ dataInfo.startFee }}元</div>
          </div>
          <div class="item">
            <div>开始时间:</div>
            <div>
              {{ dataInfo.rentBeginDate || '未开始' }}
            </div>
          </div>
          <div class="item">
            <div>结束时间:</div>
            <div>
              {{ dataInfo.rentEndDate }}
            </div>
          </div>
          <div class="item" v-if="dataInfo.timingType === 1">
            <div>超时计费方式:</div>
            <div>{{ dataInfo.renewTime + formatTimeUnit(dataInfo.renewUnit) + '/' + dataInfo.renewPrice }}元</div>
          </div>
          <div class="item" v-if="dataInfo.timingType === 2">
            <div>计费方式:</div>
            <div>{{ dataInfo.rentTime + formatTimeUnit(dataInfo.rentUnit) + '/' + dataInfo.rentPrice }}元</div>
          </div>
          <div class="item" style="width: 100%">
            <div>说明:</div>
            <div>
              {{ dataInfo.backFlag === 0 ? '如租赁消费金额超过押金，产品可自留，无需归还。' : '如租赁消费金额超过押金，订单将自动结束，产品必须归还。' }}
            </div>
          </div>
        </el-row>
        <div class="title">商户详情</div>
        <el-row>
          <div class="item">
            <div>商户名称:</div>
            <div>
              {{ dataInfo.businessName }}
            </div>
          </div>
          <div class="item">
            <div>商户联系人:</div>
            <div>
              {{ dataInfo.businessLinkName }}
            </div>
          </div>
          <div class="item">
            <div>商户联系电话:</div>
            <div>
              {{ dataInfo.businessLinkPhone }}
            </div>
          </div>
          <div class="item">
            <div>商户地址:</div>
            <div>
              {{ dataInfo.businessAddress }}
            </div>
          </div>
        </el-row>
        <div class="title">服务员详情</div>
        <el-row>
          <div class="item">
            <div>服务员姓名:</div>
            <div>
              {{ dataInfo.waiterName }}
            </div>
          </div>
          <div class="item">
            <div>服务员联系电话:</div>
            <div>
              {{ dataInfo.waiterPhone }}
            </div>
          </div>
          <div class="item">
            <div>服务员编号:</div>
            <div>
              {{ dataInfo.waiterCode }}
            </div>
          </div>
        </el-row>
        <div class="title" v-if="dataInfo.evaluateState === 1">评价详情</div>
        <el-row v-if="dataInfo.evaluateState === 1">
          <div class="item">
            <div>服务员评价:</div>
            <div>
              {{ formatScore(dataInfo.waiterScore) }}
            </div>
          </div>
          <div class="item">
            <div>商户评价:</div>
            <div>
              {{ formatScore(dataInfo.businessScore) }}
            </div>
          </div>
          <div class="item">
            <div>服务员评价详情:</div>
            <div>
              {{ dataInfo.waiterEvaluate }}
            </div>
          </div>
          <div class="item">
            <div>商户评价详情:</div>
            <div>
              {{ dataInfo.businessEvaluate }}
            </div>
          </div>
        </el-row>
      </div>
      <el-row class="bottom">
        <div class="item">
          <div>购买数量:</div>
          <div>
            {{ dataInfo.nums }}
          </div>
        </div>
        <div class="item">
          <div>订单金额:</div>
          <div>￥{{ dataInfo.payAmount }}</div>
        </div>
        <div class="item" v-if="dataInfo.packageAmount">
          <div>包装费金额:</div>
          <div>￥{{ dataInfo.packageAmount }}</div>
        </div>
        <div class="item" v-if="dataInfo.deliveryAmount">
          <div>配送费金额:</div>
          <div>￥{{ dataInfo.deliveryAmount }}</div>
        </div>
        <div class="item" v-if="dataInfo.depositAmount">
          <div>押金:</div>
          <div>￥{{ dataInfo.depositAmount }}</div>
        </div>
        <div class="item" v-if="dataInfo.promoteGain">
          <div>推广优惠金额:</div>
          <div>-￥{{ dataInfo.promoteGain }}</div>
        </div>
        <div class="item" v-if="dataInfo.lastAmount">
          <div>差价:</div>
          <div>￥{{ dataInfo.lastAmount }}</div>
        </div>
        <div class="item">
          <div>支付总金额:</div>
          <div style="color: #fe6c11">￥{{ dataInfo.realAmount }}</div>
        </div>
        <div class="item">
          <div>支付状态:</div>
          <div style="font-size: 14px">
            {{ formatPayState(dataInfo.payState) }}
          </div>
        </div>
      </el-row>
    </el-card>

    <el-dialog :visible.sync="show" center title="交易记录">
      <el-table :data="orderPays">
        <el-table-column type="index" align="center" label="序号"> </el-table-column>
        <el-table-column prop="orderNo" label="订单编号" align="center"> </el-table-column>
        <el-table-column prop="amount" label="金额" align="center"> </el-table-column>
        <el-table-column label="支付类型" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.paySign === 1" type="success" effect="dark"> 订单原价 </el-tag>
            <el-tag size="mini" v-if="scope.row.paySign === 2" type="danger" effect="dark"> 订单差价 </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="支付时间" align="center" width="90"> </el-table-column>

        <el-table-column prop="refundServiceNo" label="退款订单号" align="center"> </el-table-column>
        <el-table-column prop="refundTime" label="退款时间" align="center"> </el-table-column>
        <el-table-column prop="content" label="内容" align="center"> </el-table-column>
        <el-table-column prop="createDate" label="创建时间" align="center" width="90"> </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :visible.sync="showForm" title="修改表单" center width="700px">
      <div class="forms">
        <template v-for="(item, index) in forms">
          <h3 style="margin: 5px 0">{{ item.name }}</h3>
          <CustomForm ref="CustomForm" :list="item.list"></CustomForm>
        </template>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="modifyFormData"> 确定 </el-button>
        <el-button @click="showForm = false"> 取消 </el-button>
      </div>
    </el-dialog>
    <!-- 修改时间 -->
    <el-dialog center title="修改到达时间" :visible.sync="modifyTime.show" class="custom-size__dialog">
      <div class="modify-time" @mouseleave="modifyTime.showTime = false">
        <div class="time" @mousemove="modifyTime.showTime = true">
          <div style="color: rgb(166 166 166); cursor: pointer">
            <template v-if="!modifyTime.id">请选择到达时间</template>
            <template v-else>{{ $Utils.getOptimizeDateTwo(modifyTime.id) }}</template>
          </div>
          <i class="el-icon-arrow-down" v-show="!modifyTime.showTime"></i>
          <i class="el-icon-arrow-up" v-show="modifyTime.showTime"></i>
        </div>
        <TreeSelect :selectedId="modifyTime.id" v-show="modifyTime.showTime" :list="modifyTime.list" class="tree-select"
          @confirm="
            modifyTime.id = $event;
          modifyTime.showTime = false;
          "></TreeSelect>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="confirmModifyTime">确定</el-button>
        <el-button>取消</el-button>
      </div>
    </el-dialog>

    <!-- 代打卡 -->
    <el-dialog center title="代打卡" :visible.sync="punchClock.show" width="700px" @close="handlePunchClockClose">
      <el-form label-width="80px">
        <el-form-item label="健康状态">
          <el-radio-group v-model="punchClock.healthState">
            <el-radio :label="1">良好</el-radio>
            <el-radio :label="2">一般</el-radio>
            <el-radio :label="3">不好</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="健康描述">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="punchClock.describes" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="handlePunchClockSubmit">确定</el-button>
        <el-button @click="handlePunchClockClose">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="订单备注修改" :visible.sync="showRemark" width="30%" :before-close="editRemarkCancel">
      <span>
        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="editRemark">
        </el-input>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRemarkCancel">取 消</el-button>
        <el-button type="primary" @click="editRemarkConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="获取定位记录" :visible.sync="locationShow" width="60%" :before-close="closeLocationShow">
      <div>
        <div>
          <el-button type="primary" size="mini" @click="handleLocation">手动获取</el-button>
          <el-button type="primary" size="mini" @click="locationReload">刷新</el-button>
        </div>
        <div>
          <el-table :data="locationList">
            <el-table-column type="index" align="center" label="序号"> </el-table-column>
            <el-table-column prop="createDate" label="定位时间" align="center"> </el-table-column>
            <el-table-column prop="address" label="定位地址" align="center"> </el-table-column>
            <el-table-column label="经纬度" align="center" width="auto">
              <template slot-scope="scope">
                <div>
                  经度：{{ scope.row.longitude }}
                </div>
                <div>
                  纬度：{{ scope.row.latitude }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 查看发票 -->
    <el-image-viewer @mousewheel.native="$event.preventDefault()" v-if="showInvoice" :on-close="closeInvoice"
      :url-list="[dataInfo.invoice]" ref="elIMageViewer"> </el-image-viewer>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import OrderApi from '@/api/order/order';
import BeeperApi from "@/api/equip/beeper";
import CustomForm from './components/CustomForm.vue';
import BusinessDepartApi from '../../api/business/depart';
import TreeSelect from '../../components/TreeSelect.vue';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import BenzAMRRecorder from 'benz-amr-recorder';
export default {
  components: {
    CustomForm,
    TreeSelect,
    ElImageViewer,
  },
  data() {
    return {
      showWholePhone: false,
      locationShow: false,
      locationList: [],
      orderId: '',
      dataInfo: {},
      goodsList: [],
      orderAttrs: [],
      rescueList: [],
      srcList: [],
      forms: [],
      permissionModifyPrice: 'SYSTEM_MANAGER_ORDER_INFO_LIST_MODIFYPRICE',
      permissionPunchClock: 'SYSTEM_MANAGER_ORDER_INFO_LIST_PUNCH_CLOCK',
      permissionCheck: 'SYSTEM_MANAGER_CUSTOMER_INFO_LIST_SEE',
      show: false,
      orderPays: [
        {
          id: 1,
        },
        {
          id: 2,
        },
      ],
      showForm: false,
      departNames: '',
      urls: [],
      modifyTime: {
        show: false,
        list: [],
        id: '',
        showTime: '',
      },
      showInvoice: false,
      voiceRemark: '',
      businessVoice: '',
      punchClock: {
        show: false,
        healthState: 1,
        describes: '',
      },
      showRemark: false,
      editRemark: ''
    };
  },
  computed: {
    address() {
      let localeInfo = this.dataInfo.localeInfo;
      if (localeInfo) {
        let provinceName = localeInfo.provinceName ? localeInfo.provinceName : '';
        let cityName = localeInfo.cityName ? localeInfo.cityName : '';
        let areaName = localeInfo.areaName ? localeInfo.areaName : '';
        let streetName = localeInfo.streetName ? localeInfo.streetName : '';
        let villageName = localeInfo.villageName ? localeInfo.villageName : '';
        let address = localeInfo.address && localeInfo.address !== '待补充' ? localeInfo.address : '';
        let houseNumber = localeInfo.houseNumber ? localeInfo.houseNumber : '';
        return provinceName + cityName + areaName + streetName + villageName + address + houseNumber;
      } else {
        return '';
      }
    },
    rowkeys() {
      return this.goodsList.filter((item) => item.ogrelations && item.ogrelations.length).map((item) => item.index);
    },
  },
  filters: {
    jobTypeFilter(val) {
      if (val === 0) {
        return (val = '无');
      } else if (val === 1) {
        return (val = '取AED');
      } else if (val === 2) {
        return (val = '现场救援');
      }
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    //获取救援进度详情
    getRescueDetail() {
      OrderApi.rescueDetail({ orderId: this.$route.query.id }).then((res) => {
        this.rescueList = res.data;
      });
    },
    getBeeperCode() {
      OrderApi.getBeeperCode({ relationId: this.dataInfo.beeperId, type: 1 }).then((res) => {
        if (res.data) {
          this.srcList = [res.data];
          this.$nextTick(() => {
            this.$refs.preview.clickHandler();
          });
        }
      });
    },
    async playVoiceRemark(prop) {
      if (prop !== 'voiceRemark') this.voiceRemark && this.voiceRemark.stop();
      if (prop !== 'businessVoice') this.businessVoice && this.businessVoice.stop();
      if (this[prop].isPlaying()) {
        this[prop].stop();
      } else {
        this[prop].play();
      }
    },
    getData() {
      this.orderId = this.$route.query.id;
      OrderApi.getOrderInfo({ id: this.$route.query.id }).then((res) => {
        this.dataInfo = res.data;
        this.dataInfo.wholePhone = res.data.phone;
        if (res.data.phone) {
          res.data.phone = res.data.phone.split('');
          res.data.phone.splice(3, 4, '****');
          res.data.phone = res.data.phone.join('');
        }
        this.showWholePhone = false;

        this.dataInfo.phone = res.data.phone;
        this.goodsList = res.data.goodsList;
        this.urls = res.data.urls || [];
        this.goodsList.forEach((item, index) => {
          item.index = index;
        });
        this.orderPays = res.data.orderPays;
        this.getDepartList();
        this.handleAorderAttrs(res.data.orderAttrs);
        console.log(this.orderAttrs, 'this.orderAttrs');
        this.forms = JSON.parse(JSON.stringify(this.orderAttrs));
        this.orderAttrs.forEach((item) => {
          this.formatOrderAttrs(item.list);
        });
        this.dataInfo.tags = this.dataInfo.tags.map((item) => item.tagName).join(',');
        if (this.dataInfo.voiceRemark && this.dataInfo.voiceRemark.endsWith('.amr')) {
          this.voiceRemark = new BenzAMRRecorder();
          this.voiceRemark.initWithUrl(this.dataInfo.voiceRemark);
        }
        if (this.dataInfo.businessVoice && this.dataInfo.businessVoice.endsWith('.amr')) {
          this.businessVoice = new BenzAMRRecorder();
          this.businessVoice.initWithUrl(this.dataInfo.businessVoice);
        }
        // 急救订单需要展示服务员急救任务
        if (this.dataInfo.orderType === 11) {
          this.getRescueDetail();
        }
      });
    },
    closeInvoice() {
      this.showInvoice = false;
    },
    formatScore(val) {
      switch (val) {
        case 1:
          return '非常差';
        case 2:
          return '差';
        case 3:
          return '一般';
        case 4:
          return '满意';
        case 5:
          return '非常满意';
      }
    },
    getRowClass(row) {
      if (!row.row.ogrelations) {
        return 'row-expand-cover';
      }
    },
    handleRowKey(row) {
      return row.index;
    },
    modifyFormData() {
      let orderAttrs = [];
      this.$refs['CustomForm'].forEach((item) => {
        orderAttrs = orderAttrs.concat(item.gererateData());
      });
      const params = {
        orderId: this.orderId,
        orderAttrs: orderAttrs,
      };
      OrderApi.editFormInfo(params).then((res) => {
        this.$Utils.notifySuccess('修改成功');
        this.showForm = false;
        this.getData();
      });
    },
    handleAorderAttrs(orderAttrs) {
      let formList = [];
      let obj = null;
      for (let key in orderAttrs) {
        if (key === '0') {
          if (!orderAttrs[key].length) return;
          obj = {
            name: '附加信息',
            list: orderAttrs[key],
            introduce: orderAttrs[key][0].introduce || '',
          };
        } else {
          formList.push({
            name: orderAttrs[key][0].goodsName || orderAttrs[key][0].serverName || '附加信息',
            list: orderAttrs[key],
            introduce: orderAttrs[key][0].introduce || '',
          });
        }
      }
      if (obj) {
        formList.push(obj);
      }
      this.orderAttrs = formList;
    },
    showTimeDialog() {
      // expectedTime是预计送达时间，deliveryTime是可选时间段,selectedTime是当前选中的时间
      const { dataInfo, modifyTime } = this;
      let { expectedTime, deliveryTime } = dataInfo;

      if (!deliveryTime) return;
      const selectedTime = expectedTime;
      expectedTime = expectedTime.includes('~') ? expectedTime.split('~')[1] : expectedTime;

      const expectedTimeTimestamp = new Date(expectedTime).getTime();
      // 可选时间段，获取15分钟的整数倍,也是明天以及后五天的可选时间
      deliveryTime = this.$Utils.getMinutesIntTime(15, ...deliveryTime.split('-'));
      // 今天的可选时间
      let todayTimes = [];
      expectedTime = expectedTime.split(' ');
      // 这里的条件是判断，如果flag为true，则是今天可到否则是明天可到
      const flag = Date.now() < expectedTimeTimestamp && expectedTime[0].startsWith(this.$Utils.formatDateString(new Date(), 'yyyy-MM-dd'));
      expectedTime = expectedTime[1].split(':').slice(0, 2);
      // times是可选的，在预计到达时间后面可选到达时间

      const times = deliveryTime.filter((item) => {
        let val = item.split(':');
        val = [Number(val[0]), Number(val[1])];
        return val[0] > expectedTime[0] || (val[0] == expectedTime[0] && val[1] >= expectedTime[1]);
      });
      expectedTime = expectedTime.join(':');
      if (flag) todayTimes.push(expectedTime);
      if (todayTimes.length) {
        expectedTime = expectedTime.split(':');
        expectedTime = [Number(expectedTime[0]), Number(expectedTime[1])];
        todayTimes = todayTimes.concat(times);
      }
      // 获取五天时间
      let timeList = this.getDateList();
      timeList = timeList.map((item, index) => {
        let name = '';
        let children = [];
        switch (index) {
          case 0:
            name = '今天';
            children = todayTimes;
            break;
          case 1:
            name = '明天';
            children = flag ? deliveryTime : times;
            break;
          default:
            name = item.month + '月' + item.day + '号';
            children = deliveryTime;
        }
        return {
          name,
          id: item.name,
          children: children.map((item2) => ({
            id: item.name + ' ' + item2,
            name: item2,
          })),
        };
      });
      // 如果今天不能送出那么就不显示今天的时间
      todayTimes.length === 0 && timeList.splice(0, 1);
      modifyTime.list = timeList;
      // let timeActiveIndex = 0
      // let timeActiveId = ""
      if (!selectedTime.includes('~')) {
        timeList.find((item, index) => {
          const val = item.children.find((item2) => selectedTime.startsWith(item2.id));
          if (val) {
            // modifyTime.value = index
            modifyTime.id = val.id;
            return true;
          }
        });
      } else {
        modifyTime.id = selectedTime;
      }
      modifyTime.show = true;
    },
    // 获取最近五天的年月日
    getDateList() {
      let arr = [1, 2, 3, 4, 5];
      const date = new Date();
      arr = arr.map((_, index) => {
        const date2 = new Date(date.getTime() + index * 24 * 60 * 60 * 1000);
        const name = this.$Utils.formatDateString(date2, 'yyyy-MM-dd');
        const month = date2.getMonth() + 1;
        return {
          name,
          year: date2.getFullYear(),
          month: month < 10 ? '0' + month : month,
          day: date2.getDate(),
        };
      });
      return arr;
    },
    // 确认修改到达时间
    async confirmModifyTime() {
      await this.$confirm('确认修改到达时间？', '提示', {});
      const { modifyTime, orderId, dataInfo } = this;
      await OrderApi.setExpectedTime({ expectedTime: modifyTime.id, orderId });
      dataInfo.expectedTime = modifyTime.id;
      this.$Utils.notifySuccess('修改成功');
      modifyTime.show = false;
    },
    // 获取部门列表
    getDepartList() {
      BusinessDepartApi.listMangerTree({
        businessId: this.dataInfo.businessId,
      }).then((res) => {
        this.departList = res.data;
        this.getDepartNames();
      });
    },
    getDepartNames() {
      let departNames = '';
      const { departId, firstDepartId, secondDepartId, thirdDepartId } = this.dataInfo;
      if (thirdDepartId) {
        departNames = this.$Utils.filterTreeToArr(this.departList, { departId: thirdDepartId }, 'departId');
      } else if (secondDepartId) {
        departNames = this.$Utils.filterTreeToArr(this.departList, { departId: secondDepartId }, 'departId');
      } else if (firstDepartId) {
        departNames = this.$Utils.filterTreeToArr(this.departList, { departId: firstDepartId }, 'departId');
      } else if (departId) {
        departNames = this.$Utils.filterTreeToArr(this.departList, { departId: departId }, 'departId');
      }
      this.departNames = departNames.map((item) => item.departName).join('-');
    },
    handleClickRefund(row, index) {
      this.$confirm('该产品确定退货退款吗？', message.TITLE_PROMPT, {}).then(() => {
        let list = [{ orderGoodsId: row.orderGoodsId, nums: row.nums }];
        let param = {
          orderId: this.$route.query.id,
          list: list,
        };
        OrderApi.orderSalesReturn(param).then((res) => {
          this.goodsList.splice(index, 1);
          this.$Utils.notifySuccess('退款成功');
        });
      });
    },
    formatOrderAttrs(orderAttrs) {
      if (!orderAttrs || orderAttrs.length == 0) return;
      orderAttrs.forEach((item) => {
        let fieldOptions = item.fieldOptions ? JSON.parse(item.fieldOptions) : [];
        switch (item.fieldType) {
          case 2:
            if (item.value && fieldOptions.length) {
              item.value = item.value
                .split(',')
                .map((item) => {
                  return fieldOptions.find((item2) => {
                    if (item == item2.id) return true;
                  }).name;
                })
                .join(',');
            }
            break;
          case 3:
            if (item.value) {
              item.value = item.value.split(',').join(' - ');
            }
            break;
          case 4:
            if (item.value) {
              item.value = item.value.split(',');
            } else {
              item.value = [];
            }
            break;
          case 6:
            if (item.value && fieldOptions.length && typeof fieldOptions[0] == 'object') {
              item.value = fieldOptions.find((item2) => item2.id == item.value).name;
            }
            break;
          case 7:
            if (item.value) {
              item.value = JSON.parse(item.value).address;
            }
            break;
          // case 8:
          //   if(item.value){
          //     item.value = JSON.parse(item.value).address
          //   }
          //   break
        }
      });
    },
    formatLocaleType(cellValue) {
      if (cellValue === 1) {
        return '公共';
      } else if (cellValue === 2) {
        return '专属';
      }
    },
    formatTimeUnit(cell) {
      if (cell === 1) {
        return '分钟';
      } else if (cell === 2) {
        return '小时';
      } else if (cell === 3) {
        return '天';
      }
    },
    formatOrderState(cellValue) {
      if (cellValue === 1) {
        return '已接单待确认';
      } else if (cellValue === 5) {
        return '商户已确认';
      } else if (cellValue === 10) {
        return '服务员已确认';
      } else if (cellValue === 11) {
        return '已出发';
      } else if (cellValue === 12) {
        return '已到达';
      } else if (cellValue === 13) {
        return '已回收';
      } else if (cellValue === 15) {
        return '已取消';
      } else if (cellValue === 16) {
        return '取消失败';
      } else if (cellValue === 20) {
        return '已完成';
      }
    },
    formatPayType(cellValue) {
      if (cellValue === 1) {
        return '余额';
      } else if (cellValue === 2) {
        return '微信支付';
      } else if (cellValue === 3) {
        return '货到付款';
      } else if (cellValue === 4) {
        return '他人代付';
      } else if (cellValue === 5) {
        return '0元购';
      } else if (cellValue === 6) {
        return '线下月结';
      } else if (cellValue === 7) {
        return '线下余额';
      }
    },
    formatPayState(cellValue) {
      if (cellValue === 1) {
        return '未支付';
      } else if (cellValue === 4) {
        return '未支付差价';
      } else if (cellValue === 5) {
        return '已支付';
      } else if (cellValue === 10) {
        return '已取消';
      } else if (cellValue === 15) {
        return '已退款';
      } else if (cellValue === 20) {
        return '完成';
      }
    },
    formatAppointmentState(cellValue) {
      if (cellValue === 1) {
        return '预约中';
      } else if (cellValue === 3) {
        return '预约失败';
      } else if (cellValue === 5) {
        return '预约成功';
      } else if (cellValue === 7) {
        return '预约取消';
      }
    },
    formatOrderType(cellValue) {
      if (cellValue === 1) {
        return '普通订单';
      } else if (cellValue === 3) {
        return '计时';
      } else if (cellValue === 8) {
        return '报警';
      } else if (cellValue === 9) {
        return '语音单';
      } else if (cellValue === 10) {
        return '补贴';
      } else if (cellValue === 15) {
        return '补差价';
      } else if (cellValue === 11) {
        return '急救订单';
      }
    },
    formatEquipType(type) {
      switch (type) {
        case 1:
          return '呼叫器';
        case 2:
          return '接收器';
        case 3:
          return '烟雾报警器';
        case 4:
          return '燃气报警器';
        case 5:
          return '门磁报警器';
        case 6:
          return '水浸卫士';
        case 7:
          return '摄像头';
        case 8:
          return 'SOS报警器';
        case 9:
          return '跌倒报警器';
        case 10:
          return '红外报警器';
        case 11:
          return '睡眠监测';
        case 12:
          return '血糖仪';
        case 13:
          return '血压仪';
        case 14:
          return '动态血压仪';
        case 15:
          return '拐杖';
        case 16:
          return '胸牌';
        case 17:
          return '智护手表';
        case 18:
          return '云喇叭';
        case 19:
          return '除颤仪';
      }
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.back();
      // this.$router.push({ path: '/order/orderManagement' })
    },

    /**
     * 代打卡提交
     */
    handlePunchClockSubmit() {
      const { healthState, describes } = this.punchClock;
      const { ordersUserId } = this.dataInfo;
      OrderApi.healthClock({ healthState, describes, userId: ordersUserId }).then(() => {
        this.punchClock = { show: false, healthState: 1, describes: '' };
        this.$message.success('代打卡成功');
      });
    },
    /**
     * 代打卡关闭
     */
    handlePunchClockClose() {
      this.punchClock = { show: false, healthState: 1, describes: '' };
    },

    handleGotoCustomerList() {
      const userId = this.dataInfo.ordersUserId;
      this.$router.push({ path: '/customer/CustomerManagement', query: { userId } });
    },
    editRemarkCancel() {
      this.showRemark = false
      this.editRemark = ''
    },
    editRemarkConfirm() {
      OrderApi.editOrderRemark({
        orderId: this.$route.query.id,
        orderRemark: this.editRemark
      }).then((res) => {
        if (res.status == 0) {
          this.editRemarkCancel()
          this.$message.success('操作成功')
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
      });
    },
    handleLocation() {
      BeeperApi.sendDirectiveByMq({
        beeperId: this.dataInfo.beeperId,
        type: 1,
        originNo: this.dataInfo.originNo
      }).then(res => {
        if (res.status == 0) {
          this.$message.success('操作成功')
          this.getLocationList('N')
        }
      })
    },
    locationReload() {
      this.getLocationList('N')
      this.$message.success("已刷新")
    },
    getLocationList(state) {
      OrderApi.getLocationRecord({ orderId: this.orderId }).then(res => {
        if (res.status === 0) {
          this.locationList = res.data
          if (state != 'N') {
            this.locationShow = true
          }
        }
      })
    },
    closeLocationShow() {
      this.locationShow = false
      this.locationList = []
    },
    sendNotify() {
      this.$prompt('请输入通知内容', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',

      }).then(({ value }) => {
        BeeperApi.sendDirectiveByMq({
          beeperId: this.dataInfo.beeperId,
          content: value,
          type: 30
        }).then(res => {
          if (res.status === 0) {
            this.$message.success('发送成功')
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {

      });
    }
  },
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/views/orderDetail.scss';
</style>
<style lang="scss" scoped>
.attr-introduce {
  max-width: 800px !important;
  color: #0880f8 !important;
  padding-bottom: 6px;
}

.pay-state {
  position: relative;
  color: #35b34a;

  .el-button {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto 0;
    padding: 0 4px;
    line-height: normal;
    transform: translateX(10px);
  }
}

.el-table {
  .inner-table {
    width: 60%;
    margin: 0 auto;
  }

  ::v-deep .row-expand-cover {
    .cell {
      .el-table__expand-icon {
        display: none;
      }
    }
  }
}

.forms {
  max-height: 600px;
  overflow: auto;
}

.image-wrapper {
  display: flex;

  // justify-content:space-between;
  // flex-wrap:
  .el-image {
    margin-right: 10px;
    width: 240px;
    height: 240px;
    flex-shrink: 0;
  }
}

.modify-time {
  position: relative;
  width: 200px;

  &:hover {
    .tree-select {
      // display:flex !important;
    }
  }

  .time {
    border: 1px solid #dbdbdb;
    height: 34px;
    padding: 0 10px;
    line-height: 34px;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .tree-select {
    position: absolute;
    width: 100%;
    padding-top: 4px;
    // display:none;
  }
}

.el-icon-video-play,
.el-icon-video-pause {
  font-size: 35px;
}

.el-icon-view,
.el-icon-view,
.el-icon-edit,
.el-icon-picture-outline {
  font-size: 19px;
  margin-left: 10px;
  vertical-align: -3px;
  cursor: pointer;
}

.rightBtn {
  margin-left: auto;
}
</style>
